var form = layui.form, laydate = layui.laydate, upload = layui.upload, table = layui.table, $ = layui.jquery,
    id = getQueryVariable("id");

layui.use(['tableEdit',"selectInput"], function () {
    let layer = layui.layer,
        selectInput = layui.selectInput;

    //客户信息
    let customerInfo = [];
    //业务员
    let salesmanInfo = [];
    //客户联系人
    let customerContact = [];
    //国家
    let country = [];
    //询盘平台
    let inquiryPlatformList = [];


    if (id != "") {
        $("#oddNumber").attr("readonly", true);
    } else {
        $.ajax({
            type:'POST',
            url:'inquiry/getLatestOddNumber',
            dataType:"json",
            contentType: 'application/json;charset=utf-8',
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    if (res.data != "") {
                        form.val("editor-form", {
                            "oddNumber": res.data,
                        })
                    }
                } else {
                    layer.msg(res.msg, {icon: 5});
                }
            },
            error: function (data) {
                layer.msg(data.msg, {icon: 5});
            }
        })
        lay('.starttime').each(function () {
            laydate.render({
                elem: this,
                type: 'date',
                format: 'yyyy-MM-dd',
                value: new Date(),
            });
        });
        $("#frequency").val(1).attr("readonly", true);
    }
    let currencyList = getdictionary(5, 14);//币种列表

    //询盘平台
    inquiryPlatformList = getdictionary(6, 61);
    for (let i in inquiryPlatformList) {
        if (inquiryPlatformList[i].valid===1){
            $("#inquiryPlatformCode").append(new Option(inquiryPlatformList[i].name, inquiryPlatformList[i].code));
        }
    }

    function getCountry() {
        //获取国家信息
        $.ajax({
            url:"offer/getCountry",
            async:false,
            success:function(data){
                if(data.status == 200){
                    country = data.data;
                    for(let i in data.data){
                        $('#countryRegion').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });
    }
    //监听获取国家下拉框
    form.on("select(countryRegion)", function(data){
        if(data.value === ""){
            $("#countryRegionName").val("");
            return;
        }
        let name = getDestinationName(data.value);
        $("#countryRegionName").val(name);
    });
    function getDestinationName(code) {
        for(let i in country){
            if(country[i].code == code){
                return country[i].name;
            }
        }
        return "";
    }

    //监听询盘平台下拉框
    form.on("select(inquiryPlatformCode)", function(data){
        if(data.value === ""){
            return;
        }
        for(let i in inquiryPlatformList){
            if(data.value == inquiryPlatformList[i].code){
                $('#inquiryPlatformName').val(inquiryPlatformList[i].name);
            }
        }
    });

    //获取业务员
    function getAllUser() {
        $.ajax({
            url: "otherOutStock/getAllUserInfo",
            async: false,
            success: function (data) {
                if (data.status == 200) {
                    salesmanInfo = data.data;
                    for (let i in salesmanInfo) {
                        $("#customerSalesman").append(new Option(salesmanInfo[i].name, salesmanInfo[i].code));
                    }
                }
            }
        });
    }
    //监听业务员下拉框
    form.on("select(customerSalesman)", function(data){
        if(data.value === ""){
            $('#salesmanName').val("");
            return;
        }
        for(let i in salesmanInfo){
            if(data.value == salesmanInfo[i].code){
                $('#salesmanName').val(salesmanInfo[i].name);
                break;
            }
        }
    });

    //客户名称
    function setCustomerInfo(initData) {
        //客户名称
        let ins = selectInput.render({
            elem: '#customerSelect',
            name: 'customerSelect',
            initValue: initData,
            hasSelectIcon: true,
            placeholder: '请输入名称',
            data: [],
        })
        //监听输入
        ins.on('itemInput(customerSelect)', function (obj) {
            let tempData = [];
            $.ajax({
                url: "basicInformation/getCustomerInfo?info=" + obj.value,
                async: false,
                success: function (res) {
                    if (res.status == 200) {
                        customerInfo = res.data.customerInfo;
                        for (let i in customerInfo) {
                            customerInfo[i]["value"] = customerInfo[i].code;
                            tempData.push(customerInfo[i]);
                        }
                    }
                }
            })
            ins.addSelect(tempData)
        })

        // 监听select 选择事件
        ins.on('itemSelect(customerSelect)', function (obj) {
            let code = obj.data;
            let name = obj.textContent;
            $("#customerCode").val(code);
            $("#customerName").val(name);
            //获取客户联系人
            getCustomerContactName(code);

            for(let i in customerInfo){
                if(customerInfo[i]["code"] === code){
                    //客户简称
                    $("#customerSimpleName").val(customerInfo[i]["abbreviation"]);
                    //客户来源
                    $("#customerSource").val(customerInfo[i]["sourceOfCustomerName"]);
                    //国家
                    let countryCode = customerInfo[i]["countryCode"];
                    if(!isEmpty(countryCode)){
                        for(let j in country){
                            if(countryCode === country[j]["code"]){
                                $("#countryRegion").val(country[j]["code"]);
                                $("#countryRegionName").val(country[j]["name"]);
                                form.render('select');
                                break;
                            }
                        }
                    }
                    break;
                }
            }
        });
    }

    function getCustomerContactName(customCode) {
        //通过客户编码获取客户联系人
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:customCode,
            url:"otherOutStock/add/getCustomerContactInfo",
            async:false,
            success:function(res){
                if(res.status == 200){
                    customerContact = res.data;
                    //客户联系人重新赋值
                    $("#customerContactName").empty();
                    for(let i in res.data){
                        $('#customerContactName').append(new Option(res.data[i].name, res.data[i].name));
                    }
                    //默认选中第一个
                    if(res.data.length > 0){
                        $('#customerContactName').val(res.data[0].name);
                        $('#email').val(res.data[0].email);
                    }
                    form.render('select');
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });
    }

    //制单公司
    $.ajax({
        url: "company/getAllMakerUnit",
        success: function (res) {
            if (res.status == 200) {
                $.each(res.data, function (index, item) {
                    $("#complaintUnit").append(new Option(item.name, item.code));
                });
                form.render('select');
            } else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
    let loginUserCode = user.code;//当前登录用户编码
    let executorList = [];
    $.ajax({
        url: "user/getAllUserNameAndCode",
        success: function (res) {
            if (res.status == 200) {
                executorList = res.data;
                for (let i in res.data) {
                    $('#executorCode').append(new Option(res.data[i].name, res.data[i].code));
                }
                //获取业务员
                getAllUser();
                //获取国家
                getCountry();
                if (id != "") {
                    queryById();
                } else {
                    $('#executorCode').val(loginUserCode);
                    //客户名称
                    setCustomerInfo("");
                }
                form.render('select');
            } else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });

    for (let i in currencyList) {
        $('#currency').append(new Option(currencyList[i].name, currencyList[i].code));
    }
    form.render('select');

    let productList = [];
    let fileList = [];
    let wjCatalogCode = "Inquiry";//文件编码
    let logList = [
    ];

    //自定义表单验证
    form.verify({
        Ndouble: [
            /^[1-9]\d*$/
            , '只能输入整数哦'
        ]
    });

    //监听提交
    form.on('submit(form-element)', function (data) {
        let reqData = data.field;
        let productCache = table.cache["storageproductstableid"];
        reqData["productList"] = productCache;
        reqData["fileList"] = fileList;
        let flag = false;
        if (id == "") {
            flag = insert(reqData);
        } else {
            reqData.id = id;
            flag = update(reqData);
        }
        if (flag) {
            setTimeout(function () {
                //保存成功则刷新提交过来的界面 并关闭此页面
                parent.detab("views/jsp/other/pollingdisc.jsp");
                parent.intab("views/jsp/other/pollingdisc.jsp", "询盘")
                parent.detab("views/jsp/other/tpl/newuppollingdisc.jsp" + (id == '' ? '' : '?id=' + id));
            }, 1000);
        }
        return false;
    });
    form.on('submit(form-element2)', function (data) {
        layer.msg("保存成功", {icon: 6});
        setTimeout(function () {
            //保存成功则刷新提交过来的界面 并关闭此页面
            parent.detab("views/jsp/other/pollingdisc.jsp");
            parent.intab("views/jsp/other/pollingdisc.jsp", "询盘")
            parent.detab("views/jsp/other/tpl/newuppollingdisc.jsp" + (id == '' ? '' : '?id=' + id));
        }, 1000);
        return false;
    });

    //--产品信息
    table.render({
        elem: '#storageproducts',
        id: 'storageproductstableid',
        data: productList,
        toolbar: '#storageproductstoolbar',
        cols: [[
            {checkbox: true, fixed: true},
            {field: 'productImg', title: '图片', width: 120, align: 'center', templet: '#imgTpl'},
            {field: 'platformInquiryNo', title: '平台询价单号', edit: 'text'},
            {field: 'productNo', title: '产品编码', sort: true, width: 120, edit: 'text'},
            {field: 'specNo', title: '规格编码', sort: true, width: 120, edit: 'text'},
            {field: 'normExplain', title: '规格说明', edit: 'text', width: 120},
            {field: 'customerArticleNo', title: '客户货号', sort: true, width: 120, edit: 'text'},
            {field: 'chineseName', title: '中文名称', edit: 'text',style:"overflow:hidden" },
            {field: 'englishName', title: '英文名称', edit: 'text',style:"overflow:hidden" },
            {field: 'chineseDesc', title: '中文描述', edit: 'text',style:"overflow:hidden" },
            {field: 'englishDesc', title: '英文描述', edit: 'text',style:"overflow:hidden" },
            {field: 'amount', width: 80, title: '数量', edit: 'text'},
            {field: 'price', width: 80, title: '销售单价', edit: 'text'},
            {field: 'priceSubtotal', width: 120, title: '金额小计', edit: 'text'},
            {fixed: 'right', title: '操作', width: 100, align: 'center', toolbar: '#productsEditor'}
        ]],
        page: false,
        limit: Number.MAX_VALUE,
        height: 440,
        done: function (res, curr, count) {
            hoverOpenImg();//显示大图
        }
    });


    table.on('edit(storageproductstable)', function (obj) {
        let old = $(this).prev().text();//旧值
        //判断数据类型
        if ((obj.field == "amount" || obj.field == "price" || obj.field == "priceSubtotal"|| obj.field == "cost") && !isNumber(obj.value)) {
            layer.msg('请输入数字');
            $(this).val(old);
            return;
        }
        obj.data.price = Number(obj.data.price).toFixed(4);
        obj.update({
            price:obj.data.price,
            priceSubtotal:(obj.data.amount*obj.data.price).toFixed(2)
        })
    });

    table.on('tool(storageproductstable)', function (obj) {
        if (obj.event === 'del') {
            layer.confirm('确认删除?', function (index) {
                let oldData =  table.cache["storageproductstableid"];
                for (let i = 0; i < oldData.length; i++) {
                    if (oldData[i].tempId == obj.data.tempId) {
                        oldData.splice(i, 1);
                        i--;
                        table.reload('storageproductstableid',{data : oldData});
                        break;
                    }
                }
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
            });

        }
    });

    table.on('toolbar(storageproductstable)', function (obj) {
        let checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'importproducts':
                layer.open({
                    type: 2,
                    area: $(window).width() < 458 ? "['100%', '100%']" : ['75%', '75%'],
                    content: 'views/jsp/other/tpl/importproducts.jsp'
                });
                break;
            case 'new':
                let oldData = table.cache["storageproductstableid"];
                let newData = {
                    tempId: oldData.length + 1,
                    productImg: "",
                    productNo: "",
                    specNo: "",
                    normExplain: "",
                    customerArticleNo: "",
                    chineseName: "",
                    englishName: "",
                    chineseDesc: "",
                    englishDesc: "",
                    amount: "",
                    price: "",
                    priceSubtotal: "",
                    platformInquiryNo: ""
                };
                oldData.push(newData);
                table.reload('storageproductstableid', {data: oldData, limit : oldData.length});
                break;
            case 'delList':
                let data = checkStatus.data, delList = [];
                data.forEach(function (n, i) {
                    delList.push(n.tempId);
                });
                if (delList !='') {
                    layer.confirm('确定删除所选项吗？', function (index) {
                        let cbList = table.cache["storageproductstableid"];
                        for (let i = 0; i < cbList.length; i++) {
                            delList.forEach((item, index) => {
                                //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                                if (typeof (cbList[i]) != "undefined" && item == cbList[i].tempId) {
                                    cbList.splice(i, 1);
                                }
                            })
                        }
                        table.reload("storageproductstableid", {
                            data: cbList,
                        });
                        layer.msg('删除成功');
                    })
                } else {
                    layer.msg('请选择需要删除的行');
                }
                break;
        };
    });

    function hoverOpenImg() {
        let img_show = null; // tips提示
        $("body").delegate("td img", "mouseover", function () {
            let img = "<img class='img_msg' src='" + $(this).attr('src') + "' style='width:130px;' />";
            img_show = layer.tips(img, this, {
                tips: [2, 'rgba(41,41,41,.5)']
                , area: ['160px']
            });
        });
        $("body").delegate("td img", "mouseout", function () {
            layer.close(img_show);
        });
    }

    //附件
    table.render({
        elem: '#attachment'
        , data: fileList
        , toolbar: '#attachmenttoolbar'
        , cols: [[
            {field: 'wjName', title: '文件名称',style:"overflow:hidden"},
            // {field: 'fileName', title: '文件名称',style:"overflow:hidden"},
            {field: 'fileUrl', title: '文件路径',style:"overflow:hidden"},
            {field: 'fileType', title: '文件类型'},
            {field: 'fileSize', title: '文件大小(KB)'},
            {field: 'fileExecutor', title: '操作员',
                templet: function(data) {
                    let name = "";
                    $.each(executorList, function(index, item) {
                        if (data.fileExecutor==item.code){
                            name = item.name;
                            return ;
                        }
                    });
                    return name;
                }
            },
            {field: 'fileUploadTime', title: '上传时间',
                templet: function(d) {
                    return layui.util.toDateString(d.createTime,"yyyy-MM-dd");
                }
            },
            {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'},
        ]]
        , id: 'attachmenttableid'
        , height: 380
        , page: true
    });
    upload.render({
        elem: '#uploadfile'
        , url: 'ftp/uploadFile'
        , field: 'uploadify'
        , accept: 'file'
        , data:{"fileType":"Inquiry"}
        , multiple: true
        , auto: false
        , bindAction: '#testListAction'
        , choose: function (obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function (index, file, result) {
                var newfilename = "";
                if (ispd(wjCatalogCode, file.name)) {
                    // newfilename = getFileName(file.name);
                    // layer.msg("此目录下已存在重名的文件，已自动对本文件进行了重命名！");
                    layer.confirm('已存在同名的文件，是否覆盖？', function (index) {
                        layer.close(index);
                    });
                }
                if (newfilename != "") {
                    var obj = {};
                    obj.code = index;
                    obj.name = newfilename;
                    fileList.push(obj);
                    var tr = $(['<tr id="upload-' + index + '">'
                        , '<td>' + newfilename + '</td>'
                        , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                        , '<td>等待上传</td>'
                        , '<td>'
                        , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                        , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                        , '</td>'
                        , '</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function () {
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function () {
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        // fileListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                        var fileListIns = [];
                        for (var i = 0; i < fileList.length; i++) {
                            if (index != fileList[i].code) {
                                fileListIns.push(fileList[i]);
                            }
                        }
                        fileList = fileListIns;
                    });

                    $("#uploadlist").append(tr);
                }else{
                    var obj = {};
                    obj.code = index;
                    obj.name = file.name;
                    // fileList.push(obj);
                    var tr = $(['<tr id="upload-' + index + '">'
                        , '<td>' + file.name + '</td>'
                        , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                        , '<td>等待上传</td>'
                        , '<td>'
                        , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                        , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                        , '</td>'
                        , '</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function () {
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function () {
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        // fileListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                        var fileListIns = [];
                        for (var i = 0; i < fileList.length; i++) {
                            if (index != fileList[i].code) {
                                fileListIns.push(fileList[i]);
                            }
                        }
                        fileList = fileListIns;
                    });

                    $("#uploadlist").append(tr);
                }
            });
        }
        , done: function (res, index, upload) {
            var filename = "";
            for (var i = 0; i < uploadlist.length; i++) {
                if (uploadlist[i].code == index) {
                    filename = uploadlist[i].name;
                    break;
                }
            }
            if (res.data.length > 0) {
                var files = res.data;
                var filepaths = [];
                for (var i = 0; i < files.length; i++) {
                    var obj = {};
                    obj.fileName = files[i].fileName;
                    obj.ftpPath = files[i].ftpPath;
                    filepaths.push(obj);
                }
                if (savefile(filepaths, filename, wjCatalogCode)) {
                    let oldData = fileList;
                    let newData = [];
                    let num = oldData.length+1;
                    for(let i in files){
                        let newFile = {};
                        // fileList[i].tempId = num;
                        newFile.fileName = files[i].fileName;
                        newFile.wjName = files[i].originalFileName;
                        newFile.fileUrl = files[i].ftpPath;
                        newFile.fileSize = (this.files[index].size / 1024).toFixed(1);
                        newData.push(newFile);
                        num++;
                    }
                    oldData.push.apply(oldData, newData);
                    fileList = oldData;
                    table.reload('attachmenttableid', {data:fileList});
                }

                var tr = $("#uploadlist").find('tr#upload-' + index), tds = tr.children();
                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                tds.eq(3).html(''); //清空操作
                return delete this.files[index]; //删除文件队列已经上传成功的文件
            }
            /* if (res.files.file) { //上传成功
                 var tr = $("#uploadlist").find('tr#upload-' + index)
                     , tds = tr.children();
                 tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                 tds.eq(3).html(''); //清空操作
                 return delete this.files[index]; //删除文件队列已经上传成功的文件
             }*/
            this.error(index, upload);
        }
        , error: function (index, upload) {
            let tr = $("#uploadlist").find('tr#upload-' + index), tds = tr.children();
            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
        }
    });

    table.on('toolbar(attachmenttable)', function (obj) {
        let checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'uploadfile':
                $("#uploadlist").html(""); //清空上传列表数据
                layer.open({
                    type: 1,
                    title: "文件上传",
                    area: ['710px', '340px'],
                    content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                    , cancel: function (index, layero) {
                        table.reload('attachmenttableid', {}); //点击关闭刷新表格
                    }
                });
                break;
        };
    });
    table.on('tool(attachmenttable)', function (obj) {
        let data = obj.data;
        if (obj.event === 'download') { //下载
            downFileLoad(data.fileUrl+'/'+data.fileName);
        } else if (obj.event === 'del') {
            layer.confirm('确认删除吗？', function (index) {
                let oldData =  fileList;
                for (let i = 0; i < oldData.length; i++) {
                    if (oldData[i].tempId == obj.data.tempId) {
                        oldData.splice(i, 1);
                        i--;
                        table.reload('attachmenttableid',{data : oldData});
                        break;
                    }
                }
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
            });
        }
    });

    //操作日志
    table.render({
        elem: '#otherwarehouselog'
        , data: logList
        , cols: [[
            {field: 'operationtype', title: '操作类型'}
            , {field: 'theoperator', title: '操作员'}
            , {field: 'operationdate', title: '操作日期'}
            , {field: 'modifythecontent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 440
        , limit: 30//显示的数量
        , page: true
    });

    function isNumber(val) {
        let regPos = /^\d+(\.\d+)?$/; //非负浮点数
        let regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
        if (regPos.test(val) || regNeg.test(val)) {
            return true;
        } else {
            return false;
        }
    }

    function queryById() {
        $.ajax({
            type: 'POST',
            url: 'inquiry/selectByKey/' + id,
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    if (res.data) {
                        //客户名称
                        setCustomerInfo(res.data.customerName);
                        $("#customerCode").val(res.data.customerCode);
                        $("#customerName").val(res.data.customerName);

                        //业务员
                        $("#customerSalesman").val(res.data.customerSalesman);
                        $("#salesmanName").val(res.data.salesmanName);

                        //询盘平台
                        $("#inquiryPlatformName").val(res.data.inquiryPlatformName);
                        $("#inquiryPlatformCode").val(res.data.inquiryPlatformCode);

                        //获取客户联系人
                        getCustomerContactName(res.data.customerCode);
                        $("#customerContactName").val(res.data.customerContactName);
                        $('#email').val(res.data.email);
                        $('#countryRegion').val(res.data.countryRegion);
                        $('#countryRegionName').val(res.data.countryRegionName);
                        form.val("editor-form", {
                            "oddNumber": res.data.oddNumber,
                            "boxStatus": res.data.boxStatus,
                            "inquirer": res.data.inquirer,
                            "feedbackTime": res.data.feedbackTime,
                            "currency": res.data.currency,
                            "complaintUnit": res.data.complaintUnit,
                            "customerSimpleName": res.data.customerSimpleName,
                            "customerSource": res.data.customerSource,
                            "frequency": res.data.frequency
                        });
                        laydate.render({
                            elem: '#inquiryTime',
                            type: 'date',
                            value: new Date(res.data.inquiryTime),
                        });
                        laydate.render({
                            elem: '#feedbackTime',
                            type: 'date',
                            value: new Date(res.data.feedbackTime),
                        });
                        productList = queryProductByInId(id);
                        table.reload('storageproductstableid',{data : productList});
                        fileList = queryFileByInId(id);
                        table.reload('attachmenttableid',{data : fileList});
                    } else {
                        // layer.msg("初始化失败!");
                    }
                } else {
                    layer.msg("初始化失败!");
                }
            },
            error: function (data) {
                layer.msg("初始化失败!");
            }
        });
    }

    //产品
    function queryProductByInId(inId) {
        let resList = [];
        $.ajax({
            type: 'POST',
            url: 'inquiry/selectProductByInId/' + inId,
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    if (res.data.length > 0) {
                        resList = res.data;
                        form.val("editor-form", {
                            "productNo": res.data.productNo,
                            "specNo": res.data.specNo,
                            "normExplain": res.data.normExplain,
                            "chineseName": res.data.chineseName,
                            "englishName": res.data.englishName,
                            "chineseDesc": res.data.chineseDesc,
                            "englishDesc": res.data.englishDesc,
                            "customerArticleNo": res.data.customerArticleNo,
                            "price": res.data.price,
                            "amount": res.data.amount,
                            "priceSubtotal": res.data.priceSubtotal,
                        })
                        for (let i = 0; i < resList.length; i++) {
                            resList[i].tempId = i+1;
                        }
                        table.reload('storageproductstableid',{});
                    } else {
                        // layer.msg(res.msg, {icon: 0})
                    }
                } else {
                    layer.msg(res.msg,{icon:3});
                }
            },
            error: function (data) {
                layer.msg("产品初始化失败!");
            }
        });
        return resList;
    }

//附件
    function queryFileByInId(inId) {
        let resList = [];
        $.ajax({
            type: 'POST',
            url: 'inquiry/selectFileByInId/' + inId,
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    if (res.data.length > 0) {
                        resList = res.data;
                        form.val("editor-form", {
                            "wjName": res.data.wjName,
                            "fileUrl": res.data.fileUrl,
                            "fileType": res.data.fileType,
                            "fileSize": res.data.fileSize,
                            "fileExecutor": res.data.fileExecutor,
                            "fileUploadTime": res.data.fileUploadTime,
                        })
                    } else {
                    }
                } else {
                    layer.msg(res.msg,{icon:3});
                }
            },
            error: function (data) {
                layer.msg("附件初始化失败!");
            }
        });
        return resList;
    }

    function insert(data) {
        let tf = false;
        $.ajax({
            type: 'POST',
            data: JSON.stringify(data),
            url: 'inquiry/insert',
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    if (res.data>0) {
                        tf = true;
                        layer.msg("添加成功!");
                    } else {
                        layer.msg(res.msg+" 添加失败");
                    }
                } else {
                    layer.msg(res.msg);
                }
            },
            error: function (data) {
                layer.msg("添加失败!");
            }
        });
        return tf;
    }

    function update(data) {
        let tf = false;
        $.ajax({
            type: 'POST',
            data: JSON.stringify(data),
            url: 'inquiry/update',
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    tf = true;
                    layer.msg("修改成功!");
                } else {
                    layer.msg("修改失败!");
                }
            },
            error: function (data) {
                layer.msg("修改失败!");
            }
        });
        return tf;
    }
    //获取文件目录下所有的文件名
    function ispd(wjCatalogCode, filename) {
        var cun = false;
        $.ajax({
            type: 'get',
            data: {"wjCatalogCode": wjCatalogCode, "name": filename},
            url: 'wjinfo/ispd',
            dataType: "json",
            async: false,
            success: function (da) {
                if (da.status == 200) {
                    cun = da.data == 0 ? false : true;

                }
            },
            error: function (data) {
                // layer.msg("获取失败!");
            }
        });
        return cun;
    }

    function getFileName(filename) {
        /* fileNames=[];*/
        var cun = "";
        $.ajax({
            type: 'get',
            data: {"filename": filename},
            url: 'wjinfo/getFileName',
            dataType: "json",
            async: false,
            success: function (da) {
                if (da.status == 200) {
                    cun = da.data;

                }
            },
            error: function (data) {
                // layer.msg("获取失败!");
            }
        });
        return cun;
    }

    //判断文件名是否重复
    function iscf(filename) {
        var tf = false;
        for (var i = 0; i < fileNames.length; i++) {
            if (filename == fileNames[i]) {
                tf = true;
                break;
            }
        }
        return tf;
    }

    //保存上传的文件
    function savefile(filepaths, filename, wjCatalogCode) {
        var tf = false;
        $.ajax({
            type: 'post',
            data: {
                "files": JSON.stringify(filepaths), "wjCatalogCode": JSON.stringify(wjCatalogCode),
                "name": JSON.stringify(filename)
            },
            url: 'wjinfo/savefile',
            dataType: "json",
            async: false,
            success: function (da) {
                if (da.status == 200) {
                    tf = da.data == 0 ? false : true;
                }
            },
            error: function (data) {
                // layer.msg("获取失败!");
            }
        });
        return tf;
    }
})

//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}